//
//  YSDBManage.m
//  Yaoyle
//
//  Created by ZhaoXudong on 14-9-23.
//  Copyright (c) 2014年 ZhaoXudong. All rights reserved.
//

#import "YSDBManage.h"


#define kDefaultDBName @"agentCar.sqlite"

#define PATH_OF_DOCUMENT [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0]

static YSDBManage *shareManage = nil;

@implementation YSDBManage

- (id)init {
    self = [super init];
    if (self) {
        int state = [self initialDBWithName:kDefaultDBName];
        if (state == -1) {
            NSLog(@"数据库初始化失败");
        }
    }
    return self;
}

- (int)initialDBWithName:(NSString *)name {
    if (!name) {
        return -1;
    }
    //沙盒目录
    NSString * document = PATH_OF_DOCUMENT;
    filePath = [document stringByAppendingString:[NSString stringWithFormat:@"/%@", name]];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    BOOL exist = [fileManager fileExistsAtPath:filePath];
    
    [self connect];
    
    if (!exist) {
        return 0;
    } else {
        return 1;
    }
}

+ (YSDBManage *)shareManage {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareManage = [[YSDBManage alloc] init];
        NSString * document = PATH_OF_DOCUMENT;
        NSString * sourcrPath = [document stringByAppendingPathComponent:kDefaultDBName];
        shareManage.dbPath = sourcrPath;
    });
    return shareManage;
}

- (void)connect {
    if (!_dataBase) {
        _dataBase = [[FMDatabase alloc] initWithPath:filePath];
    }
    if (![_dataBase open]) {
        NSLog(@"不能打开数据库");
    }
}

- (void)close {
    [_dataBase close];
    shareManage = nil;
}

@end
